<template>
  <div class="setting-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">系统设置</h1>
        </div>
        <el-button type="primary" @click="saveSettings" class="save-settings-btn">
          保存设置
        </el-button>
      </div>
    </div>
    
    <!-- 设置表单 -->
    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
            class="mt-4"
          >
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">网站信息</h3>
            
            <el-form-item label="网站名称" prop="siteName">
              <el-input v-model="basicForm.siteName" placeholder="请输入网站名称"></el-input>
            </el-form-item>
            
            <el-form-item label="网站描述" prop="siteDescription">
              <el-input 
                v-model="basicForm.siteDescription" 
                type="textarea" 
                rows="2"
                placeholder="请输入网站描述"
              ></el-input>
            </el-form-item>
            
            <el-form-item label="网站Logo">
              <div class="flex items-center">
                <div 
                  class="w-16 h-16 border border-dashed border-gray-300  rounded flex items-center justify-center mr-4 overflow-hidden"
                >
                  <img v-if="basicForm.siteLogo" :src="basicForm.siteLogo" class="max-w-full max-h-full" />
                  <el-icon v-else class="text-gray-400"><i class="el-icon-picture"></i></el-icon>
                </div>
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleLogoChange"
                >
                  <el-button type="primary" plain>选择图片</el-button>
                </el-upload>
              </div>
              <div class="text-gray-500 text-xs mt-1">建议尺寸: 200x200px，支持 PNG, JPG, SVG 格式</div>
            </el-form-item>
            
            <el-form-item label="网站图标">
              <div class="flex items-center">
                <div 
                  class="w-10 h-10 border border-dashed border-gray-300  rounded flex items-center justify-center mr-4 overflow-hidden"
                >
                  <img v-if="basicForm.siteFavicon" :src="basicForm.siteFavicon" class="max-w-full max-h-full" />
                  <el-icon v-else class="text-gray-400"><i class="el-icon-picture"></i></el-icon>
                </div>
                <el-upload
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleFaviconChange"
                >
                  <el-button type="primary" plain>选择图片</el-button>
                </el-upload>
              </div>
              <div class="text-gray-500 text-xs mt-1">建议尺寸: 32x32px，支持 ICO, PNG 格式</div>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">SEO设置</h3>
            
            <el-form-item label="SEO标题" prop="seoTitle">
              <el-input v-model="basicForm.seoTitle" placeholder="请输入SEO标题"></el-input>
            </el-form-item>
            
            <el-form-item label="SEO关键词" prop="seoKeywords">
              <el-input 
                v-model="basicForm.seoKeywords" 
                type="textarea" 
                rows="2"
                placeholder="请输入SEO关键词，多个关键词用英文逗号分隔"
              ></el-input>
            </el-form-item>
            
            <el-form-item label="SEO描述" prop="seoDescription">
              <el-input 
                v-model="basicForm.seoDescription" 
                type="textarea" 
                rows="3"
                placeholder="请输入SEO描述"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 抓取设置 -->
        <el-tab-pane label="抓取设置" name="crawler">
          <el-form
            ref="crawlerFormRef"
            :model="crawlerForm"
            :rules="crawlerRules"
            label-width="180px"
            class="mt-4"
          >
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">全局抓取配置</h3>
            
            <el-form-item label="默认抓取间隔(秒)" prop="defaultInterval">
              <el-input-number 
                v-model="crawlerForm.defaultInterval" 
                :min="1" 
                :max="3600"
                controls-position="right"
              ></el-input-number>
              <div class="text-gray-500 text-xs mt-1">两次抓取请求之间的最小间隔时间，避免请求过于频繁</div>
            </el-form-item>
            
            <el-form-item label="请求超时时间(秒)" prop="requestTimeout">
              <el-input-number 
                v-model="crawlerForm.requestTimeout" 
                :min="1" 
                :max="60"
                controls-position="right"
              ></el-input-number>
              <div class="text-gray-500 text-xs mt-1">单个请求的最大等待时间</div>
            </el-form-item>
            
            <el-form-item label="最大重试次数" prop="maxRetries">
              <el-input-number 
                v-model="crawlerForm.maxRetries" 
                :min="0" 
                :max="10"
                controls-position="right"
              ></el-input-number>
              <div class="text-gray-500 text-xs mt-1">请求失败后的最大重试次数</div>
            </el-form-item>
            
            <el-form-item label="并发抓取任务数" prop="concurrentTasks">
              <el-input-number 
                v-model="crawlerForm.concurrentTasks" 
                :min="1" 
                :max="20"
                controls-position="right"
              ></el-input-number>
              <div class="text-gray-500 text-xs mt-1">同时运行的最大抓取任务数</div>
            </el-form-item>
            
            <el-form-item label="默认User-Agent" prop="userAgent">
              <el-input 
                v-model="crawlerForm.userAgent" 
                type="textarea" 
                rows="2"
                placeholder="请输入默认User-Agent"
              ></el-input>
              <div class="text-gray-500 text-xs mt-1">抓取请求使用的默认User-Agent</div>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">代理设置</h3>
            
            <el-form-item label="启用代理">
              <el-switch v-model="crawlerForm.enableProxy"></el-switch>
            </el-form-item>
            
            <template v-if="crawlerForm.enableProxy">
              <el-form-item label="代理类型" prop="proxyType">
                <el-select v-model="crawlerForm.proxyType">
                  <el-option label="HTTP" value="http"></el-option>
                  <el-option label="HTTPS" value="https"></el-option>
                  <el-option label="SOCKS5" value="socks5"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="代理服务器" prop="proxyServer">
                <el-input v-model="crawlerForm.proxyServer" placeholder="例如: 127.0.0.1:8080"></el-input>
              </el-form-item>
              
              <el-form-item label="代理认证">
                <el-switch v-model="crawlerForm.proxyAuth"></el-switch>
              </el-form-item>
              
              <template v-if="crawlerForm.proxyAuth">
                <el-form-item label="代理用户名" prop="proxyUsername">
                  <el-input v-model="crawlerForm.proxyUsername" placeholder="请输入代理用户名"></el-input>
                </el-form-item>
                
                <el-form-item label="代理密码" prop="proxyPassword">
                  <el-input 
                    v-model="crawlerForm.proxyPassword" 
                    type="password" 
                    placeholder="请输入代理密码"
                    show-password
                  ></el-input>
                </el-form-item>
              </template>
            </template>
          </el-form>
        </el-tab-pane>
        
        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form
            ref="notificationFormRef"
            :model="notificationForm"
            :rules="notificationRules"
            label-width="150px"
            class="mt-4"
          >
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">邮件通知</h3>
            
            <el-form-item label="启用邮件通知">
              <el-switch v-model="notificationForm.enableEmail"></el-switch>
            </el-form-item>
            
            <template v-if="notificationForm.enableEmail">
              <el-form-item label="SMTP服务器" prop="smtpServer">
                <el-input v-model="notificationForm.smtpServer" placeholder="例如: smtp.example.com"></el-input>
              </el-form-item>
              
              <el-form-item label="SMTP端口" prop="smtpPort">
                <el-input-number 
                  v-model="notificationForm.smtpPort" 
                  :min="1" 
                  :max="65535"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
              
              <el-form-item label="加密方式" prop="smtpEncryption">
                <el-select v-model="notificationForm.smtpEncryption">
                  <el-option label="无" value="none"></el-option>
                  <el-option label="SSL" value="ssl"></el-option>
                  <el-option label="TLS" value="tls"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="发件人邮箱" prop="smtpUsername">
                <el-input v-model="notificationForm.smtpUsername" placeholder="请输入发件人邮箱"></el-input>
              </el-form-item>
              
              <el-form-item label="邮箱密码/授权码" prop="smtpPassword">
                <el-input 
                  v-model="notificationForm.smtpPassword" 
                  type="password" 
                  placeholder="请输入邮箱密码或授权码"
                  show-password
                ></el-input>
              </el-form-item>
              
              <el-form-item label="发件人名称" prop="smtpSender">
                <el-input v-model="notificationForm.smtpSender" placeholder="请输入发件人名称"></el-input>
              </el-form-item>
              
              <el-form-item label="测试收件人" prop="testEmail">
                <div class="flex">
                  <el-input v-model="notificationForm.testEmail" placeholder="请输入测试收件人邮箱"></el-input>
                  <el-button type="primary" class="ml-2" @click="testEmailSend">发送测试</el-button>
                </div>
              </el-form-item>
            </template>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">通知事件</h3>
            
            <el-form-item label="任务失败通知">
              <el-switch v-model="notificationForm.notifyTaskFailure"></el-switch>
              <div class="text-gray-500 text-xs mt-1">当抓取任务执行失败时发送通知</div>
            </el-form-item>
            
            <el-form-item label="系统错误通知">
              <el-switch v-model="notificationForm.notifySystemError"></el-switch>
              <div class="text-gray-500 text-xs mt-1">当系统发生错误时发送通知</div>
            </el-form-item>
            
            <el-form-item label="新闻审核通知">
              <el-switch v-model="notificationForm.notifyNewsReview"></el-switch>
              <div class="text-gray-500 text-xs mt-1">当有新闻需要审核时发送通知</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 高级设置 -->
        <el-tab-pane label="高级设置" name="advanced">
          <el-form
            ref="advancedFormRef"
            :model="advancedForm"
            :rules="advancedRules"
            label-width="150px"
            class="mt-4"
          >
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">缓存设置</h3>
            
            <el-form-item label="启用页面缓存">
              <el-switch v-model="advancedForm.enablePageCache"></el-switch>
              <div class="text-gray-500 text-xs mt-1">启用后可提高页面加载速度</div>
            </el-form-item>
            
            <el-form-item label="缓存过期时间(分钟)" prop="pageCacheExpire" v-if="advancedForm.enablePageCache">
              <el-input-number 
                v-model="advancedForm.pageCacheExpire" 
                :min="1" 
                :max="1440"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
            
            <el-form-item label="启用API缓存">
              <el-switch v-model="advancedForm.enableApiCache"></el-switch>
              <div class="text-gray-500 text-xs mt-1">启用后可减轻服务器负担</div>
            </el-form-item>
            
            <el-form-item label="API缓存过期时间(秒)" prop="apiCacheExpire" v-if="advancedForm.enableApiCache">
              <el-input-number 
                v-model="advancedForm.apiCacheExpire" 
                :min="1" 
                :max="3600"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">安全设置</h3>
            
            <el-form-item label="启用API限流">
              <el-switch v-model="advancedForm.enableRateLimit"></el-switch>
              <div class="text-gray-500 text-xs mt-1">限制API请求频率，防止恶意请求</div>
            </el-form-item>
            
            <el-form-item label="限流阈值(次/分钟)" prop="rateLimitThreshold" v-if="advancedForm.enableRateLimit">
              <el-input-number 
                v-model="advancedForm.rateLimitThreshold" 
                :min="1" 
                :max="1000"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
            
            <el-form-item label="启用CORS">
              <el-switch v-model="advancedForm.enableCors"></el-switch>
              <div class="text-gray-500 text-xs mt-1">允许跨域资源共享</div>
            </el-form-item>
            
            <el-form-item label="允许的域名" prop="corsAllowedOrigins" v-if="advancedForm.enableCors">
              <el-input 
                v-model="advancedForm.corsAllowedOrigins" 
                type="textarea" 
                rows="3"
                placeholder="请输入允许的域名，多个域名用英文逗号分隔，例如: https://example.com,https://api.example.com"
              ></el-input>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">系统维护</h3>
            
            <el-form-item>
              <div class="flex space-x-4">
                <el-button type="warning" @click="clearCache">
                  <el-icon class="mr-1"><i class="el-icon-delete"></i></el-icon>清除缓存
                </el-button>
                <el-button type="danger" @click="confirmResetSystem">
                  <el-icon class="mr-1"><i class="el-icon-refresh"></i></el-icon>重置系统
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 界面特效设置 -->
        <el-tab-pane label="界面特效设置" name="effects">
          <el-form
            ref="effectsFormRef"
            :model="effectsForm"
            :rules="effectsRules"
            label-width="180px"
            class="mt-4"
          >
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">首页特效</h3>
            
            <el-form-item label="启用太阳系特效">
              <el-switch v-model="effectsForm.enableSolarSystem"></el-switch>
              <div class="text-gray-500 text-xs mt-1">在首页显示3D太阳系模型，关闭后将完全停止渲染以节省性能</div>
            </el-form-item>
            
            <el-form-item label="太阳系大小" v-if="effectsForm.enableSolarSystem">
              <el-select v-model="effectsForm.solarSystemSize" placeholder="请选择太阳系大小">
                <el-option label="小尺寸 (60x60)" value="small"></el-option>
                <el-option label="中尺寸 (80x80)" value="medium"></el-option>
                <el-option label="大尺寸 (100x100)" value="large"></el-option>
              </el-select>
              <div class="text-gray-500 text-xs mt-1">调整太阳系模型的显示大小</div>
            </el-form-item>
            
            <el-form-item label="太阳系位置" v-if="effectsForm.enableSolarSystem">
              <el-select v-model="effectsForm.solarSystemPosition" placeholder="请选择太阳系位置">
                <el-option label="标题右侧" value="title-right"></el-option>
                <el-option label="页面右上角" value="top-right"></el-option>
                <el-option label="页面中央" value="center"></el-option>
              </el-select>
              <div class="text-gray-500 text-xs mt-1">调整太阳系模型在页面中的位置</div>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">性能优化</h3>
            
            <el-form-item label="自动暂停渲染">
              <el-switch v-model="effectsForm.autoPauseRendering"></el-switch>
              <div class="text-gray-500 text-xs mt-1">当页面不可见时自动暂停3D渲染以节省性能</div>
            </el-form-item>
            
            <el-form-item label="渲染质量" v-if="effectsForm.enableSolarSystem">
              <el-select v-model="effectsForm.renderQuality" placeholder="请选择渲染质量">
                <el-option label="低质量 (性能优先)" value="low"></el-option>
                <el-option label="中等质量 (平衡)" value="medium"></el-option>
                <el-option label="高质量 (效果优先)" value="high"></el-option>
              </el-select>
              <div class="text-gray-500 text-xs mt-1">调整3D渲染质量，影响性能和视觉效果</div>
            </el-form-item>
            
            <el-divider></el-divider>
            
            <h3 class="text-lg font-medium mb-4 text-slate-800 ">预览</h3>
            
            <el-form-item>
              <div class="bg-gray-50 p-4 rounded-lg">
                <div class="flex items-center justify-between mb-2">
                  <span class="text-sm font-medium text-gray-700">当前设置预览</span>
                  <el-button type="primary" size="small" @click="previewEffects">预览效果</el-button>
                </div>
                <div class="text-xs text-gray-500 space-y-1">
                  <div>太阳系特效: {{ effectsForm.enableSolarSystem ? '已启用' : '已禁用' }}</div>
                  <div v-if="effectsForm.enableSolarSystem">
                    <div>大小: {{ getSolarSystemSizeText(effectsForm.solarSystemSize) }}</div>
                    <div>位置: {{ getSolarSystemPositionText(effectsForm.solarSystemPosition) }}</div>
                    <div>渲染质量: {{ getRenderQualityText(effectsForm.renderQuality) }}</div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'


// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

// 当前激活的标签页
const activeTab = ref('basic')

// 表单引用
const basicFormRef = ref(null)
const crawlerFormRef = ref(null)
const notificationFormRef = ref(null)
const advancedFormRef = ref(null)
const effectsFormRef = ref(null)

// 基本设置表单
const basicForm = ref({
  siteName: '新闻聚合平台',
  siteDescription: '汇聚全球新闻，提供最新、最全面的新闻资讯',
  siteLogo: '',
  siteFavicon: '',
  seoTitle: '新闻聚合平台 - 汇聚全球新闻资讯',
  seoKeywords: '新闻,资讯,聚合,全球新闻,时事,热点',
  seoDescription: '新闻聚合平台是一个汇聚全球新闻的资讯平台，提供最新、最全面的新闻资讯，涵盖政治、经济、科技、文化等多个领域。'
})

// 抓取设置表单
const crawlerForm = ref({
  defaultInterval: 5,
  requestTimeout: 10,
  maxRetries: 3,
  concurrentTasks: 5,
  userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
  enableProxy: false,
  proxyType: 'http',
  proxyServer: '',
  proxyAuth: false,
  proxyUsername: '',
  proxyPassword: ''
})

// 通知设置表单
const notificationForm = ref({
  enableEmail: false,
  smtpServer: '',
  smtpPort: 465,
  smtpEncryption: 'ssl',
  smtpUsername: '',
  smtpPassword: '',
  smtpSender: '新闻聚合平台',
  testEmail: '',
  notifyTaskFailure: true,
  notifySystemError: true,
  notifyNewsReview: false
})

// 高级设置表单
const advancedForm = ref({
  enablePageCache: true,
  pageCacheExpire: 30,
  enableApiCache: true,
  apiCacheExpire: 60,
  enableRateLimit: true,
  rateLimitThreshold: 100,
  enableCors: false,
  corsAllowedOrigins: ''
})

// 界面特效设置表单
const effectsForm = ref({
  enableSolarSystem: true,
  solarSystemSize: 'medium',
  solarSystemPosition: 'title-right',
  autoPauseRendering: true,
  renderQuality: 'medium'
})

// 表单验证规则
const basicRules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  siteDescription: [
    { required: true, message: '请输入网站描述', trigger: 'blur' },
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  seoTitle: [
    { required: true, message: '请输入SEO标题', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ],
  seoKeywords: [
    { required: true, message: '请输入SEO关键词', trigger: 'blur' },
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  seoDescription: [
    { required: true, message: '请输入SEO描述', trigger: 'blur' },
    { max: 300, message: '长度不能超过 300 个字符', trigger: 'blur' }
  ]
}

const crawlerRules = {
  defaultInterval: [
    { required: true, message: '请输入默认抓取间隔', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于等于 1', trigger: 'blur' }
  ],
  requestTimeout: [
    { required: true, message: '请输入请求超时时间', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于等于 1', trigger: 'blur' }
  ],
  maxRetries: [
    { required: true, message: '请输入最大重试次数', trigger: 'blur' },
    { type: 'number', min: 0, message: '必须大于等于 0', trigger: 'blur' }
  ],
  concurrentTasks: [
    { required: true, message: '请输入并发抓取任务数', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于等于 1', trigger: 'blur' }
  ],
  userAgent: [
    { required: true, message: '请输入默认User-Agent', trigger: 'blur' }
  ],
  proxyServer: [
    { required: true, message: '请输入代理服务器', trigger: 'blur', validator: (rule, value, callback) => {
      if (crawlerForm.value.enableProxy && !value) {
        callback(new Error('请输入代理服务器'))
      } else {
        callback()
      }
    }}
  ],
  proxyUsername: [
    { required: true, message: '请输入代理用户名', trigger: 'blur', validator: (rule, value, callback) => {
      if (crawlerForm.value.enableProxy && crawlerForm.value.proxyAuth && !value) {
        callback(new Error('请输入代理用户名'))
      } else {
        callback()
      }
    }}
  ],
  proxyPassword: [
    { required: true, message: '请输入代理密码', trigger: 'blur', validator: (rule, value, callback) => {
      if (crawlerForm.value.enableProxy && crawlerForm.value.proxyAuth && !value) {
        callback(new Error('请输入代理密码'))
      } else {
        callback()
      }
    }}
  ]
}

const notificationRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationForm.value.enableEmail && !value) {
        callback(new Error('请输入SMTP服务器'))
      } else {
        callback()
      }
    }}
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationForm.value.enableEmail && !value) {
        callback(new Error('请输入SMTP端口'))
      } else {
        callback()
      }
    }}
  ],
  smtpUsername: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationForm.value.enableEmail && !value) {
        callback(new Error('请输入发件人邮箱'))
      } else {
        callback()
      }
    }}
  ],
  smtpPassword: [
    { required: true, message: '请输入邮箱密码/授权码', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationForm.value.enableEmail && !value) {
        callback(new Error('请输入邮箱密码/授权码'))
      } else {
        callback()
      }
    }}
  ],
  smtpSender: [
    { required: true, message: '请输入发件人名称', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationForm.value.enableEmail && !value) {
        callback(new Error('请输入发件人名称'))
      } else {
        callback()
      }
    }}
  ],
  testEmail: [
    { pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

const advancedRules = {
  pageCacheExpire: [
    { required: true, message: '请输入缓存过期时间', trigger: 'blur', validator: (rule, value, callback) => {
      if (advancedForm.value.enablePageCache && !value) {
        callback(new Error('请输入缓存过期时间'))
      } else {
        callback()
      }
    }}
  ],
  apiCacheExpire: [
    { required: true, message: '请输入API缓存过期时间', trigger: 'blur', validator: (rule, value, callback) => {
      if (advancedForm.value.enableApiCache && !value) {
        callback(new Error('请输入API缓存过期时间'))
      } else {
        callback()
      }
    }}
  ],
  rateLimitThreshold: [
    { required: true, message: '请输入限流阈值', trigger: 'blur', validator: (rule, value, callback) => {
      if (advancedForm.value.enableRateLimit && !value) {
        callback(new Error('请输入限流阈值'))
      } else {
        callback()
      }
    }}
  ],
  corsAllowedOrigins: [
    { required: true, message: '请输入允许的域名', trigger: 'blur', validator: (rule, value, callback) => {
      if (advancedForm.value.enableCors && !value) {
        callback(new Error('请输入允许的域名'))
      } else {
        callback()
      }
    }}
  ]
}

const effectsRules = {
  solarSystemSize: [
    { required: true, message: '请选择太阳系大小', trigger: 'change' }
  ],
  solarSystemPosition: [
    { required: true, message: '请选择太阳系位置', trigger: 'change' }
  ],
  renderQuality: [
    { required: true, message: '请选择渲染质量', trigger: 'change' }
  ]
}

// 处理Logo上传
const handleLogoChange = (file) => {
  // 这里应该是实际的文件上传逻辑
  // 模拟上传成功后返回URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    basicForm.value.siteLogo = reader.result
  }
}

// 处理Favicon上传
const handleFaviconChange = (file) => {
  // 这里应该是实际的文件上传逻辑
  // 模拟上传成功后返回URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    basicForm.value.siteFavicon = reader.result
  }
}

// 发送测试邮件
const testEmailSend = () => {
  if (!notificationForm.value.testEmail) {
    ElMessage.warning('请输入测试收件人邮箱')
    return
  }
  
  // 验证邮箱格式
  const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
  if (!emailRegex.test(notificationForm.value.testEmail)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }
  
  // 这里应该是实际的发送测试邮件逻辑
  ElMessage({
    type: 'info',
    message: '正在发送测试邮件...',
  })
  
  ElMessage({
    type: 'success',
    message: `测试邮件已发送至 ${notificationForm.value.testEmail}`,
  })
}

// 清除缓存
const clearCache = () => {
  ElMessageBox.confirm(
    '确定要清除所有缓存吗？这可能会导致系统短暂变慢。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 这里应该是实际的清除缓存逻辑
    ElMessage({
      type: 'success',
      message: '缓存已清除',
    })
  }).catch(() => {
    // 取消操作
  })
}

// 确认重置系统
const confirmResetSystem = () => {
  ElMessageBox.confirm(
    '确定要重置系统吗？这将清除所有数据并恢复到初始状态，此操作不可逆！',
    '危险操作',
    {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      type: 'error',
      distinguishCancelAndClose: true,
      confirmButtonClass: 'el-button--danger',
    }
  ).then(() => {
    // 二次确认
    ElMessageBox.prompt('请输入 "RESET" 以确认重置系统', '二次确认', {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      inputPattern: /^RESET$/,
      inputErrorMessage: '请输入 "RESET" 以确认',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
    }).then(({ value }) => {
      // 这里应该是实际的重置系统逻辑
      ElMessage({
        type: 'success',
        message: '系统已重置，即将刷新页面...',
      })
      
      window.location.reload()
    }).catch(() => {
      // 取消操作
    })
  }).catch(() => {
    // 取消操作
  })
}

// 保存设置
const saveSettings = () => {
  // 验证所有表单
  const validateForms = async () => {
    try {
      // 根据当前激活的标签页验证对应的表单
      if (activeTab.value === 'basic') {
        await basicFormRef.value.validate()
      } else if (activeTab.value === 'crawler') {
        await crawlerFormRef.value.validate()
      } else if (activeTab.value === 'notification') {
        await notificationFormRef.value.validate()
      } else if (activeTab.value === 'advanced') {
        await advancedFormRef.value.validate()
      } else if (activeTab.value === 'effects') {
        await effectsFormRef.value.validate()
      }
      
      // 保存界面特效设置到localStorage
      if (activeTab.value === 'effects' && process.client) {
        localStorage.setItem('solarSystemSettings', JSON.stringify(effectsForm.value))
        
        // 如果关闭了太阳系，通知用户需要刷新页面
        if (!effectsForm.value.enableSolarSystem) {
          ElMessage({
            type: 'warning',
            message: '太阳系特效已关闭，请刷新首页以完全停止渲染',
          })
        } else {
          ElMessage({
            type: 'success',
            message: '界面特效设置已保存',
          })
        }
      } else {
        // 这里应该是实际的保存设置逻辑
        ElMessage({
          type: 'success',
          message: '设置已保存',
        })
      }
    } catch (error) {
      // 表单验证失败
      return false
    }
  }
  
  validateForms()
}

// 获取太阳系大小文本
const getSolarSystemSizeText = (size) => {
  const sizeMap = {
    small: '小尺寸 (60x60)',
    medium: '中尺寸 (80x80)',
    large: '大尺寸 (100x100)'
  }
  return sizeMap[size] || '中尺寸 (80x80)'
}

// 获取太阳系位置文本
const getSolarSystemPositionText = (position) => {
  const positionMap = {
    'title-right': '标题右侧',
    'top-right': '页面右上角',
    'center': '页面中央'
  }
  return positionMap[position] || '标题右侧'
}

// 获取渲染质量文本
const getRenderQualityText = (quality) => {
  const qualityMap = {
    low: '低质量 (性能优先)',
    medium: '中等质量 (平衡)',
    high: '高质量 (效果优先)'
  }
  return qualityMap[quality] || '中等质量 (平衡)'
}

// 预览特效
const previewEffects = () => {
  // 保存当前设置到localStorage
  if (process.client) {
    localStorage.setItem('solarSystemSettings', JSON.stringify(effectsForm.value))
  }
  
  // 提示用户
  if (effectsForm.value.enableSolarSystem) {
    ElMessage({
      type: 'success',
      message: '太阳系特效已启用，请访问首页查看效果',
    })
  } else {
    ElMessage({
      type: 'info',
      message: '太阳系特效已禁用，请刷新首页以完全停止渲染',
    })
  }
}

// 初始化
onMounted(() => {
  // 这里应该是实际的加载设置逻辑
  // 已经在表单初始化时设置了默认值
  
  // 从localStorage加载太阳系设置
  if (process.client) {
    const savedSettings = localStorage.getItem('solarSystemSettings')
    if (savedSettings) {
      try {
        const settings = JSON.parse(savedSettings)
        effectsForm.value = { ...effectsForm.value, ...settings }
      } catch (error) {
        console.error('加载太阳系设置失败:', error)
      }
    }
  }
})
</script>

<style scoped>
/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
}

:deep(.el-divider__text) {
  background-color: var(--el-bg-color);
}


/* 卡片样式 */
:deep(.el-card__body) {
  padding: 20px;
}

/* 输入框样式 */
:deep(.el-textarea__inner) {
  font-family: inherit;
}

/* 标题样式 */
h3 {
  margin-top: 10px;
  color: var(--el-text-color-primary);
}

/* 保存设置按钮样式 */
.save-settings-btn {
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.save-settings-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.save-settings-btn .el-icon {
  font-size: 16px;
}

.save-settings-btn span {
  font-size: 14px;
  letter-spacing: 0.5px;
}
</style>